package com.siwei.mes.sync.erp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.config.UidUtils;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.erp.Itemorder;
import com.siwei.mes.entity.erp.Rwdextra;
import com.siwei.mes.entity.erp.RwdextraInfo;
import com.siwei.mes.entity.experiment.*;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.enums.*;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.experiment.*;
import com.siwei.mes.service.experiment.ExperimentService;
import com.siwei.mes.sync.erp.service.GenConcreteService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生成抗氯离子试验委托
 *
 * @Description: 生成抗氯离子试验委托
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/1/8 16:45
 */
@Service
public class GenKllzExperimentService extends GenConcreteService {
    private static final Logger log = LoggerFactory.getLogger("erp");
    @Resource
    private ExperimentGenConfigMapper experimentGenConfigMapper;
    @Resource
    private ExperimentService experimentService;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private ExperimentSampleSmokeMapper experimentSampleSmokeMapper;
    @Resource
    private ExperimentYearConfigMapper experimentYearConfigMapper;
    @Resource
    private ExperimentSampleTestProjectMapper experimentSampleTestProjectMapper;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;

    private String TEST_PROJECT_CODE = TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode();

    /**
     * 生成抗氯离子试验委托
     *
     * @param rwdextra           任务单
     * @param itemorder          小票
     * @param testProjectInfoMap 试验委托信息
     * @return
     */
    public Long genExperiment(Rwdextra rwdextra, Itemorder itemorder, Map<String, TestProjectInfo> testProjectInfoMap) {
        try {
            log.info("生成混凝土抗氯离子开始，任务单号：【{}】，小票id；【{}】", rwdextra.getFrwdh(), itemorder.getItid());
            RwdextraInfo rwdextraInfo = rwdextra.getRwdextraInfo();
            if (rwdextraInfo == null) {
                log.info("混凝土生成抗氯离子对应任务单扩展信息为空，暂不生成，任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }
            String tpz = itemorder.getTpz();
            if (StringUtils.isBlank(tpz)) {
                log.info("混凝土砼品种为空，暂不生成，砼品种：【{}】，任务单：【{}】，小票id：【{}】", tpz, rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }
            /**这里需要CL  比如C30CL3.0*/
            String fTbj = rwdextra.getRwdextraInfo().getFTbj();
            String kllz = rwdextra.getRwdextraInfo().getKllz();
            if (StringUtils.isBlank(kllz)) {
                log.info("混凝土抗氯离子对应氯离子含量为空，暂不生成，砼品种：【{}】，任务单：【{}】，小票id：【{}】,对应fTbj值：【{}】", tpz, rwdextra.getFrwdh(), itemorder.getItid(), fTbj);
                return null;
            }

            log.info("混凝土抗氯离子对应的砼品种为：【{}】，氯离子含量：【{}】", tpz, kllz);

            ExperimentGenConfig genConfig = experimentGenConfigMapper.selectOne(new ExperimentGenConfig()
                    .setTestCode(TEST_PROJECT_CODE).setExperimentType(MaterialsEnum.CONCRETE.getCode()));

            if (genConfig == null) {
                log.info("混凝土生成抗氯离子委托规则配置为空，暂不生成，任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }

            String fPhbNo = rwdextra.getPhbshow();//配合比
            String fGcmc = rwdextraInfo.getFGcmc();//工程名称
            String ksdj = rwdextraInfo.getKsdj();

            log.info("开始组装混凝土【抗氯离子】对应试验委托，抗氯离子：【{}】，配合比号：【{}】,砼品种：【{}】，工程名称：【{}】，任务单号：【{}】，小票id：：【{}】",
                    kllz, fPhbNo, tpz, fGcmc, rwdextra.getFrwdh(), itemorder.getItid());

            if (genConfig.getIsOpen() == null || genConfig.getIsOpen() == 0) {
                log.info("混凝土{}生成委托规则配置暂未开启，暂不生成！任务单：【{}】，小票id：【{}】", genConfig.getTestName(), rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }

            int isProjectWithMix = genConfig.getIsProjectWithMix() == null ? 0 : genConfig.getIsProjectWithMix();
            int isYear = genConfig.getIsYear() == null ? 0 : genConfig.getIsYear();


            if (isProjectWithMix == 0 && isYear == 0) {
                log.info("混凝土{}生成委托规则配置未开启同工程同配合或限定未当年，暂不生成", genConfig.getTestName());
                return null;
            }

            /**委托试验名称*/
            Set<String> entrustExperimentSet = new HashSet<>();
            /**试验项目code集合*/
            Set<String> testProjectCodeList = new HashSet<>();

            TestProjectInfo projectInfo = testProjectInfoMap.get(genConfig.getTestCode());

            if (projectInfo == null) {
                log.info("混凝土生成抗氯离子对应试验项目配置未配置，暂不生成！任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }

            /**获取所有试验项目配置*/
            List<TestProjectInfo> testProjectInfoList = new ArrayList<>();
            testProjectInfoList.add(projectInfo);
            testProjectCodeList.add(projectInfo.getTestCode());
            entrustExperimentSet.add(projectInfo.getTestName());

            Long experimentId = null;

            /**这里获取当年对应的数据 是否有*/
            ExperimentYearConfig selectYearConfig = new ExperimentYearConfig().setExperimentType(MaterialsEnum.CONCRETE.getCode())
                    .setTestCode(genConfig.getTestCode()).setTestName(genConfig.getTestName());

            if (isProjectWithMix == 1) {
                selectYearConfig.setGcmc(fGcmc);
                selectYearConfig.setPhb(fPhbNo);

                if (StringUtils.isBlank(fGcmc) || StringUtils.isBlank(fPhbNo)) {
                    log.info("混凝土生成抗氯离子对应工程名称或配合比为空，暂不生成！任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                    return null;
                }
            }
            if (isYear == 1) {
                selectYearConfig.setYearNo(DateHelper.getYear());
            }

            List<ExperimentYearConfig> yearConfigList = experimentYearConfigMapper.getList(selectYearConfig);
            ExperimentYearConfig yearConfig = null;
            if (!yearConfigList.isEmpty()) {
                yearConfig = yearConfigList.get(0);
            }

            if (yearConfig == null) {
                /**如果当年的没有需要生成新的试验委托数据*/
                String entrustExperiment = entrustExperimentSet.stream().map(String::valueOf).collect(Collectors.joining(","));

                /**新增混凝土试验台账*/
                Experiment experiment = experimentService.getExperimentInfoByItemOrderInfo(itemorder, CheckEnum.BATCH.getCode(), entrustExperiment, testProjectCodeList);
                experiment.setPhb(fPhbNo);
                experiment.setKsdj(ksdj);

                /**组装物料相关信息*/
                super.payloadMaterialsInfo(itemorder.getTpz(), experiment);
                /** 协会相关信息，通过企业配置信息赋值**/
                String sampleNo = UidUtils.genNoNumberToYearStr(GenerateCodeEnum.KLLZ_SAMPLENO.getCode(), "%06d", "12");
                String consignId = UidUtils.genNoNumberToYearStr(GenerateCodeEnum.KLLZ_CONSIGNID.getCode(), "%06d", "12");
                String kllzReportId = GenerateCodeEnum.KLLZ_REPORTID.getCode() + DateHelper.getYear() + UidUtils.genNoNumber(GenerateCodeEnum.KLLZ_REPORTID.getCode(), "%05d");
                experiment.setSampleNo(sampleNo);
                experiment.setReportNo(kllzReportId);
                experiment.setReportDate(new Date());
                experiment.setCreateType(CreateTypeEnum.DEFAULT_CHECK.getCode()).setCreateCheckType(CheckTypeEnum.DEFAULT_CHECK.getCode());
                experimentMapper.insertSelective(experiment);
                experimentId = experiment.getId();

                ShxhSynchronizedata shxhInfo = shxhSynchronizedataMapper.selectByExperimentIdOne(experimentId);
                if (shxhInfo == null) {
                    //新增对应关系
                    ShxhSynchronizedata synchronizedata = new ShxhSynchronizedata().setSampleId(sampleNo)
                            .setSampleNo(sampleNo).setConsignId(consignId).setExperimentId(experimentId);
                    shxhSynchronizedataMapper.insertSelective(synchronizedata);
                } else {
                    shxhInfo.setSampleId(sampleNo)
                            .setSampleNo(sampleNo).setConsignId(consignId).setExperimentId(experimentId);
                    shxhSynchronizedataMapper.updateByPrimaryKeySelective(shxhInfo);
                }


                if (!testProjectCodeList.isEmpty()) {
                    List<ExperimentDetail> detailList = new ArrayList<>();
                    /**查询所有试验项目信息*/
                    for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                        ExperimentDetail detail = new ExperimentDetail();
                        detail.setExperimentId(experiment.getId());
                        detail.setCheckType(CheckEnum.BATCH.getCode());
                        detail.erpInit(true);
                        detail.setTestProjectCode(testProjectInfo.getTestCode());
                        detail.setTestProjectName(testProjectInfo.getTestName());
                        detail.setObjJson(testProjectInfo.getObjJson());
                        detailList.add(detail);
                    }
                    if (!detailList.isEmpty()) {
                        /**生成对应试验台账详情信息*/
                        experimentDetailMapper.insertList(detailList);
                    }

                    /**这里要过滤掉抗渗等级  抗渗等级是有压试块的*/
                    List<String> filterTestProjectCode = new ArrayList<>();
                    filterTestProjectCode.add(TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode());
                    filterTestProjectCode.add(TestProjectEnum.CONCRETE_PARAM_KYQD.getCode());
                    /**这里要查询不需要过滤的*/
                    if (!filterTestProjectCode.contains(genConfig.getTestCode())) {
                        /**新增对应快检的抽样信息  对应快检的所有的项目集合只有一条数据 */
                        ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke();
                        sampleSmoke.setId(null);
                        sampleSmoke.erpInit(true);
                        sampleSmoke.setExperimentId(experiment.getId());
                        sampleSmoke.setSampleTime(new Date());
                        sampleSmoke.setIsTestBlock(0);// 是否是试块 1-是 0-不是
                        sampleSmoke.setSamplePersonName(experiment.getEntrustPersonName());
                        sampleSmoke.setDisposerPersonName(experiment.getEntrustPersonName());

                        StringBuilder testProjectCode = new StringBuilder();
                        StringBuilder testProjectName = new StringBuilder();

                        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                            testProjectCode.append(testProjectInfo.getTestCode()).append(",");
                            testProjectName.append(testProjectInfo.getTestName()).append(",");
                        }
                        if (testProjectCode.length() > 0) {
                            String code = testProjectCode.deleteCharAt(testProjectCode.length() - 1).toString();
                            sampleSmoke.setTestProjectCode(code);
                        }
                        if (testProjectName.length() > 0) {
                            String name = testProjectName.deleteCharAt(testProjectName.length() - 1).toString();
                            sampleSmoke.setTestProjectName(name);
                            sampleSmoke.setSampleUse(name);
                        }
                        experimentSampleSmokeMapper.insertSelective(sampleSmoke);
                    }
                }

                /**如果是批检 并且在抽样试验项目配置中 有记录 直接生成对应的抽样记录 pk_experiment_sample_test_project*/
                List<ExperimentSampleSmoke> sampleSmokeList = new ArrayList<>();
                List<ExperimentSampleTestProject> sampleTestProjectList = experimentSampleTestProjectMapper.selectByTestProjectCodeList(testProjectCodeList);
                for (ExperimentSampleTestProject sampleTestProject : sampleTestProjectList) {
                    Integer genNumber = sampleTestProject.getGenNumber();// 生成的条数
                    JSONObject genJson = sampleTestProject.getGenJson();// 生成对应的json
                    if (genJson.isEmpty() || genNumber == null || genNumber == 0) {
                        continue;
                    }
                    ExperimentSampleSmoke sampleSmoke = this.getExperimentSampleSmoke(sampleTestProject, experiment, null);
                    sampleSmokeList.add(sampleSmoke);
                }
                /**保存抽样信息*/
                if (!sampleSmokeList.isEmpty()) {
                    experimentSampleSmokeMapper.insertList(sampleSmokeList);
                }

                /**这里新增对应的当年数据*/
                selectYearConfig.setId(null);
                selectYearConfig.setExperimentId(experiment.getId());
                selectYearConfig.setExperimentNo(experiment.getExperimentNo());
                selectYearConfig.setCreateTime(new Date());
                experimentYearConfigMapper.insertSelective(selectYearConfig);
            } else {
                experimentId = yearConfig.getExperimentId();
            }

            /**插入试验台账对应小票数据和试验台账对应ERP任务单记录*/
            super.insertExperimentRelatedRecords(experimentId, itemorder.getItid(), rwdextra.getFrwdh());
            /**修改试验台账的代表数量*/
            super.updateExperimentBehalfNumber(experimentId);
            log.info("生产混凝土抗氯离子完成！对应试验委托id：【{}】", experimentId);
            return experimentId;
        } catch (Exception e) {
            super.handleException("混凝土生成抗氯离子失败", e);
            return null;
        }
    }
}
